#!/usr/bin/python
import os, sys, time, threading
sys.path.append('../')
from pb import *
#############################################################
server_ip = "192.168.1.250"
server_port = 8800

try:
    (first_token, max_players) = (int(sys.argv[1]), int(sys.argv[2]))
except:
    (first_token, max_players) = (1000, 60)
    
print "%s, %s %d\n" %(server_ip ,server_port,  os.getpid())
print "first_token: %d, max players count %d\n" %(first_token, max_players)
 
class worker (threading.Thread): 
    def __init__(self, token, passwd):  
        threading.Thread.__init__(self)        
        self.thread_stop = False
        self.gid = 0
        self.token = token
        self.passwd = passwd
        
        self.sock = socket.socket(socket.AF_INET,socket.SOCK_STREAM)        
        self.sock.connect((server_ip, server_port))
        
        login(self.sock, self.token, self.passwd)
        
    def stop(self):        
        self.thread_stop = True  
   
   #Overwrite run() method, put what you want the thread do here  
    def run(self):   
        #print "%s worker" %(token)
        buf = ""
        while not self.thread_stop:  
            recv_buf = self.sock.recv(65535)
            buf = buf + recv_buf
                        
            code_len =  get_code_len(buf)
            #print "============================ %d, %d" %(code_len, (len(buf)))
            while code_len > 0 and len(buf) >= code_len:            
                (total_len, buf) =  decode_int(buf)
                (head_len, head, buf) =  head_parser(buf)
                if total_len > head_len + 9:                     
                    (body_len, buf) =  decode_int(buf)
                else:
                    body_len = 0

                #print "%d, %d, %d, %d"  %(total_len, head_len, body_len, head.msgid)        
                
                if head.msgret != 0 :
                    print "server return err %s, %d, %d" %(self.token, head.msgret, head.msgid)                    
                    break                    
                
                if head.msgid == 1003:
                    login = MsgAnsLogin ()            
                    (ret, login, buf) = body_parser (login, body_len, buf)
                    if ret != 0:
                        break
                        
                    self.gid = login.gid
                    random_move (self.sock, self.gid, 102)
                    #print login
                elif head.msgid == 1009:
                     move = MsgAnsMoveTo ()
                     (ret, move, buf) = body_parser (move, body_len, buf)                    
                     if move.gid == self.gid:
                        random_move (self.sock, self.gid, 102)
                else:            
                    buf = buf[body_len+1:]

                code_len = get_code_len (buf)     
        self.sock.close()

def main_run(): 
    thread_list = []
    for i in range(max_players) :
        token = repr(first_token + i)
        thread = worker(token, "hc2013")
        thread_list.append (thread)
    
    for i in range(len(thread_list)) :    
        thread_list[i].start()       
    
    while threading.active_count() > 1:
        # alive_thread = 0
        # for i in range(len(thread_list)) :    
            # if thread_list[i].isAlive():                
                # alive_thread += 1    
        print "%d thread is alive" %threading.active_count()
        print "please input cmd: " 
        keyboard_input =  raw_input()
        print "your input is: %s" %keyboard_input
        if keyboard_input == 'q':            
            for i in range(len(thread_list)) :    
                thread_list[i].stop()
            return;
            
        #time.sleep(0.5)
    return

if __name__ == '__main__':  
    main_run()